package cn.middle.remote.handler.decodec;

import java.util.List;

import cn.middle.remote.message.LoginSignal;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;

//消息ID + 用户名+用户密码 +客户端标识　　
public class LoginSignalCodec implements Codec<LoginSignal> {

    private int mutableLength = 4 + 4 + 4 + 4;
	@Override
	public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, int beginIndex) throws Exception {
		if(in.readableBytes() < mutableLength) {
			in.readerIndex(beginIndex);
			return ;
		}
		
		int msgLength = in.readInt();
		
		if(!CodecUtil.checkLength(in, msgLength + 4 + 4 + 4, beginIndex)) {
			return ;
		}
		String msgId = CodecUtil.context(in, msgLength);
		int usernameLength = in.readInt();
		if(!CodecUtil.checkLength(in, usernameLength + 4 + 4, beginIndex)) {
			return ;
		}
		String username = CodecUtil.context(in, usernameLength);
		int passwordLength = in.readInt();
		if(!CodecUtil.checkLength(in, usernameLength + 4, beginIndex)) {
			return ;
		}
		String password = CodecUtil.context(in, passwordLength);
		Integer clientId = in.readInt();
		
		LoginSignal singal = new LoginSignal();
		singal.setId(msgId);
		singal.setUsername(username);
		singal.setPassword(password);
		singal.setClientId(clientId);
		out.add(singal);
		
		
	}

	
	

	@Override
	public void encode(ChannelHandlerContext ctx, LoginSignal msg, ByteBuf out) throws Exception {
		out.writeBytes(msg.toData());
	}

}
